package com.meiyu.live.tv.widget;

import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.RequestCallbackWrapper;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.constant.MsgDirectionEnum;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.msg.model.QueryDirectionEnum;
import com.netease.nimlib.sdk.msg.model.RecentContact;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.meiyu.live.BaseActivity;
import com.meiyu.live.R;
import com.meiyu.live.comm.UserConfig;
import com.meiyu.live.popj.PersonalInfo;
import com.meiyu.live.popj.RelationInfo;
import com.meiyu.live.util.ToastUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zbl on 2016/9/7.
 * 私信管理显示view
 */
public class PrivateMessageView extends FrameLayout implements View.OnClickListener {

    public final static int STATE_GROUP = 0;
    public final static int STATE_MESSAGE = 1;

    public final static int MESSAGE_HISTORY_LIMIT = 100;

    private BaseActivity activity;
    private PrivateMessageViewListener listener;
    private LayoutInflater inflater;
    private ImageLoader imageLoader;
    private DisplayImageOptions options;

    private View layout_message_state;
    private View btn_send, btn_back;
    private EditText et_private_input;
    private ListView listview_privategroup, listview_privatemessage;
    private GroupAdapter groupAdapter;
    private MessageAdapter messageAdapter;

    private List<RecentContact> recentsList = new ArrayList<>();
    private List<IMMessage> messageList = new ArrayList<>();

    private int currentState = STATE_GROUP;

    private String chatNeteaseId;
    private String myNeteaseId;
    private String avatarUrl;

    private Handler handler = new Handler();

    public interface PrivateMessageViewListener {
        void onBack();

        void onNewMessage();
    }

    public PrivateMessageView(Context context) {
        super(context);
        init(context);
    }

    public PrivateMessageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context) {
        imageLoader = ImageLoader.getInstance();
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.icon_def_header)          // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.drawable.icon_def_header)  // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.icon_def_header)       // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)                          // 设置下载的图片是否缓存在SD卡中
                .build();
        PersonalInfo personalInfo = UserConfig.getInstance().getPersonalInfo();
        if (personalInfo != null) {
            avatarUrl = personalInfo.getAvatar();
        }
        myNeteaseId = UserConfig.getInstance().getNet_ease();

        activity = (BaseActivity) context;
        inflater = LayoutInflater.from(context);
        inflater.inflate(R.layout.view_privatemessage, this);
        layout_message_state = findViewById(R.id.layout_message_state);

        btn_back = findViewById(R.id.btn_private_back);
        btn_back.setOnClickListener(this);
        et_private_input = (EditText) findViewById(R.id.et_private_input);
        btn_send = findViewById(R.id.btn_private_send);
        btn_send.setOnClickListener(this);

        listview_privategroup = (ListView) findViewById(R.id.listview_privategroup);
        groupAdapter = new GroupAdapter();
        listview_privategroup.setAdapter(groupAdapter);

        listview_privatemessage = (ListView) findViewById(R.id.listview_privatemessage);
        messageAdapter = new MessageAdapter();
        listview_privatemessage.setAdapter(messageAdapter);

        initIM();
        setState(STATE_GROUP);
    }

    private Observer<List<IMMessage>> incomingMessageObserver = new Observer<List<IMMessage>>() {
        @Override
        public void onEvent(List<IMMessage> messages) {
            // 处理新收到的消息，为了上传处理方便，SDK 保证参数 messages 全部来自同一个聊天对象。
            if (messages != null) {
                if (listener != null) {
                    listener.onNewMessage();
                }
                handler.removeCallbacks(getRecentContactsTask);
                handler.postDelayed(getRecentContactsTask, 1000);
                for (IMMessage message : messages) {
                    if (message.getSessionType() == SessionTypeEnum.P2P) {
                        if (currentState == STATE_GROUP) {
//                            getRecentContacts();
                        } else if (currentState == STATE_MESSAGE) {
                            if (chatNeteaseId != null && myNeteaseId != null && (chatNeteaseId.equals(message.getSessionId()) || myNeteaseId.equals(message.getSessionId()))) {
                                messageList.add(message);
                            }
                        }
                    }
                }
                messageAdapter.notifyDataSetChanged();
                listview_privatemessage.setSelection(listview_privatemessage.getBottom());
            }
        }
    };

    private Runnable getRecentContactsTask = new Runnable() {
        @Override
        public void run() {
            getRecentContacts();
        }
    };

    private void initIM() {
        NIMClient.getService(MsgServiceObserve.class)
                .observeReceiveMessage(incomingMessageObserver, true);
        getRecentContacts();
    }

    private void destroyIM() {
        NIMClient.getService(MsgServiceObserve.class)
                .observeReceiveMessage(incomingMessageObserver, false);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        destroyIM();
    }

    private void getRecentContacts() {
        NIMClient.getService(MsgService.class).queryRecentContacts().setCallback(new RequestCallbackWrapper<List<RecentContact>>() {
            @Override
            public void onResult(int code, List<RecentContact> recents, Throwable e) {
                // recents参数即为最近联系人列表（最近会话列表）
                recentsList.clear();
                if (recents != null) {
                    for (RecentContact contact : recents) {
                        if (contact.getSessionType() == SessionTypeEnum.P2P) {
                            recentsList.add(contact);
                        }
                    }

                    if (recentsList.size() > 0) {
                        List<String> uuids = new ArrayList<>();
                        for (RecentContact contact : recentsList) {
                            uuids.add(contact.getRecentMessageId());
                        }
                        final List<IMMessage> messageList = NIMClient.getService(MsgService.class).queryMessageListByUuidBlock(uuids);
                        if (messageList != null) {
                            for (int i = 0; i < messageList.size() && i < recentsList.size(); i++) {
                                recentsList.get(i).setExtension(messageList.get(i).getRemoteExtension());
                            }
                        }
                    }
                }
                groupAdapter.notifyDataSetChanged();
            }
        });
    }

    private Comparator<IMMessage> messageComparator = new Comparator<IMMessage>() {
        @Override
        public int compare(IMMessage msg0, IMMessage msg1) {
            return msg0.getTime() > msg1.getTime() ? 1 : -1;
        }
    };

    private void getMessageList(String sessionId) {
        NIMClient.getService(MsgService.class)
                .queryMessageListEx(MessageBuilder.createEmptyMessage(sessionId, SessionTypeEnum.P2P, 0), QueryDirectionEnum.QUERY_OLD, MESSAGE_HISTORY_LIMIT, false)
                .setCallback(new RequestCallback<List<IMMessage>>() {
                    @Override
                    public void onSuccess(List<IMMessage> param) {
                        messageList.clear();
                        if (param != null) {
                            messageList.addAll(param);
                        }
                        Collections.sort(messageList, messageComparator);
                        messageAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFailed(int code) {

                    }

                    @Override
                    public void onException(Throwable exception) {

                    }
                });
    }

    @Override
    public void onClick(View view) {
        if (view == btn_send) {
            sendMessage(et_private_input.getText().toString().trim());
        } else if (view == btn_back) {
            if (currentState == STATE_GROUP) {
                if (listener != null) {
                    listener.onBack();
                }
            } else {
                getRecentContacts();
                setState(STATE_GROUP);
            }
        }
    }

    private HashMap<String, Object> remoteMap = new HashMap<>();

    private void sendMessage(String messageText) {
        if (TextUtils.isEmpty(messageText) || TextUtils.isEmpty(chatNeteaseId)) {
            return;
        }
        PersonalInfo personalInfo = UserConfig.getInstance().getPersonalInfo();
        if (personalInfo != null) {
            remoteMap.put("name", personalInfo.getName());
            remoteMap.put("avatar", personalInfo.getAvatar());
        }
        RelationInfo relationInfo = UserConfig.getInstance().getRelationInfo();
        if (relationInfo != null) {
            remoteMap.put("level", relationInfo.getLevel());
        }
        remoteMap.put("net_ease_id", UserConfig.getInstance().getNet_ease());
        remoteMap.put("user_id", UserConfig.getInstance().getLogingAccount());
        IMMessage message = MessageBuilder.createTextMessage(
                chatNeteaseId, // 聊天对象的 ID，如果是单聊，为用户帐号，如果是群聊，为群组 ID
                SessionTypeEnum.P2P, // 聊天类型，单聊或群组
                messageText // 文本内容
        );
        message.setRemoteExtension(remoteMap);
// 发送消息。如果需要关心发送结果，可设置回调函数。发送完成时，会收到回调。如果失败，会有具体的错误码。
        NIMClient.getService(MsgService.class).sendMessage(message, true);
        et_private_input.setText("");

        messageList.add(message);
        messageAdapter.notifyDataSetChanged();
        listview_privatemessage.setSelection(listview_privatemessage.getBottom());
    }

    private void setState(int state) {
        currentState = state;
        switch (state) {
            case STATE_GROUP:
                listview_privategroup.setVisibility(View.VISIBLE);
                layout_message_state.setVisibility(View.GONE);
                activity.hideSoftInputFromWindow(et_private_input);
                break;
            case STATE_MESSAGE:
                listview_privategroup.setVisibility(View.GONE);
                layout_message_state.setVisibility(View.VISIBLE);
                break;
        }
    }

    public void startPrivateMessage(String neteaseId) {
        if (TextUtils.isEmpty(neteaseId)) {
            ToastUtil.show("暂时无法联系");
            return;
        }
        chatNeteaseId = neteaseId;
        getMessageList(chatNeteaseId);
        setState(STATE_MESSAGE);
    }

    public void setListener(PrivateMessageViewListener listener) {
        this.listener = listener;
    }

    class GroupAdapter extends BaseAdapter {

        class GroupViewHolder {
            ImageView iv_avatar;
            TextView tv_name, tv_content, tv_level;
            View btn_message_detail;
        }

        @Override
        public int getCount() {
            return recentsList.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup viewGroup) {
            GroupViewHolder holder;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.adapter_privatemessage_group, null);
                holder = new GroupViewHolder();
                holder.iv_avatar = (ImageView) convertView.findViewById(R.id.iv_avatar);
                holder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
                holder.tv_content = (TextView) convertView.findViewById(R.id.tv_content);
                holder.tv_level = (TextView) convertView.findViewById(R.id.tv_level);
                holder.btn_message_detail = convertView.findViewById(R.id.btn_message_detail);
                holder.btn_message_detail.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        int p = (int) view.getTag();
                        RecentContact contact = recentsList.get(p);
                        chatNeteaseId = contact.getContactId();
                        getMessageList(chatNeteaseId);
                        setState(STATE_MESSAGE);
                    }
                });
                convertView.setTag(holder);
            } else {
                holder = (GroupViewHolder) convertView.getTag();
            }
            holder.btn_message_detail.setTag(position);
            RecentContact contact = recentsList.get(position);
            Map<String, Object> remoteMap = contact.getExtension();
            if (remoteMap != null) {
                imageLoader.displayImage((String) remoteMap.get("avatar"), holder.iv_avatar, options);
                holder.tv_name.setText((String) remoteMap.get("name"));
                Integer level = (Integer) remoteMap.get("level");
                if (level != null) {
                    holder.tv_level.setText("lv." + level);
                } else {
                    holder.tv_level.setText("lv.0");
                }
            }
            holder.tv_content.setText(contact.getContent());
            return convertView;
        }
    }


    class MessageAdapter extends BaseAdapter {

        class MessageViewHolder {
            TextView tv_content;
            ImageView iv_avatar;
        }

        @Override
        public int getCount() {
            return messageList.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public int getViewTypeCount() {
            return 2;
        }

        @Override
        public int getItemViewType(int position) {
            return messageList.get(position).getDirect() == MsgDirectionEnum.Out ? 1 : 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup viewGroup) {
            MessageViewHolder holder;
            if (convertView == null) {
                int type = getItemViewType(position);
                int viewRes;
                if (type == 0) {
                    viewRes = R.layout.adapter_live_private_message_left;
                } else {
                    viewRes = R.layout.adapter_live_private_message_right;
                }
                convertView = inflater.inflate(viewRes, null);
                holder = new MessageViewHolder();
                holder.iv_avatar = (ImageView) convertView.findViewById(R.id.iv_avatar);
                holder.tv_content = (TextView) convertView.findViewById(R.id.tv_content);
                convertView.setTag(holder);
            } else {
                holder = (MessageViewHolder) convertView.getTag();
            }
            IMMessage message = messageList.get(position);
            Map<String, Object> remoteMap = message.getRemoteExtension();
            if (remoteMap != null) {
                imageLoader.displayImage((String) remoteMap.get("avatar"), holder.iv_avatar, options);
            }
            holder.tv_content.setText(message.getContent());
            return convertView;
        }
    }
}
